#include<iostream>
#include<string.h>
#include<stdlib.h>
#include<cerrno>
#include<stdio.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#include<sys/types.h>
#include<sys/socket.h>
using namespace std;
void Usage(const string& proc)
{
    cout << "Usage:\t" << "proc server_ip server_port"<<endl;
}
// ./udp_client server_ip server_port
int main(int argc,char* argv[])
{
    if(argc != 3)
    {
        Usage(argv[0]);
        exit(1);
    }
    int sock = socket(AF_INET,SOCK_DGRAM,0);
    if(sock < 0)
    {
        perror("sock:");
        exit(2);
    }
    //客户端不需要显示的进行绑定

    struct sockaddr_in server; //填写的是服务器的网络信息
    server.sin_addr.s_addr = inet_addr(argv[1]);//字符串IP->整数IP
    server.sin_port = htons(atoi(argv[2]));//字符串端口号->主机序整数端口号->网络字节序端口号
    server.sin_family = AF_INET;

    socklen_t len = sizeof(server);
    //请求服务
    bool quit = false;
#define SIZE 1024
    char msg[SIZE] = {0};//键盘输入数据
    char buffer[SIZE] = {0};//响应
    while(!quit)
    {
        memset(msg,0,sizeof(msg));
        //从键盘输入内容,然后发送给服务端,再接收服务端的响应
        fgets(msg,sizeof(msg)-1,stdin);
        sendto(sock,msg,sizeof(msg),0,(struct sockaddr*)&server,len);

        struct sockaddr_in tmp;
        memset(buffer,0,sizeof(buffer));
        socklen_t len = sizeof(tmp);
        ssize_t ret = recvfrom(sock,buffer,sizeof(buffer)-1,0,(struct sockaddr*)&tmp,&len);
        if(ret > 0)
        {
            buffer[ret] = '\0';
            cout << "server:#" <<" " << buffer<<endl;
        }
        else
        {
            cerr << "recvfrom error" << endl;
        }
        
    }
    return 0;
}